# from asgiref.sync import async_to_sync
# from channels.layers import get_channel_layer
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, get_object_or_404, redirect
from django.template.loader import render_to_string
from django.urls import reverse_lazy, reverse
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.views.generic import CreateView, DetailView, UpdateView, ListView, DeleteView
from django.contrib import messages
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest
from django.core.mail import send_mail
from django.template import loader

from blueapps.account.decorators import login_exempt
# from blueking.component.client import ComponentClient, conf

from youpu.models import User, VerifyCode, News, Article, Question, Answer, Message, Notification, add_one_notification, \
    add_today_energy, HotList, Wordcloud
from youpu.utils import youpu_login_required, AuthorRequiredMixin, ajax_required
from youpu.forms import ArticleForm, QuestionForm

import random
import hashlib


# 由于正版用户系统被蓝鲸占了，咱只能做个盗版的了。
# 该类用于实现用户注册
# @method_decorator(login_exempt, name='dispatch')
# class UserCreateView(CreateView):
#     template_name = 'youpu/users/register.html'
#     model = User
#     form_class = RegisterBootstrapForm
#     success_url = reverse_lazy("youpu:login")


@login_exempt
def register(request):
    if request.method == 'POST':
        email = request.POST["email"]
        code = request.POST["code"]
        username = request.POST["username"]
        password = request.POST["password"]
        # 1、检查验证码
        random_code = VerifyCode.getCode(email)
        if (code != random_code):
            messages.error(request, "验证码错误！")
            # return reverse("youpu:users_register",kwargs={"request":request})
            return render(request, "youpu/users/register.html")
        # 2、检查用户名是否可用
        if (User.objects.filter(username=username).count() != 0):
            messages.error(request, "用户名已存在！")
            return render(request, "youpu/users/register.html")
            # return reverse("youpu:users_register", kwargs={"request": request})
        # 3、保存到数据库
        enc_password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
        User(email=email, username=username, password=enc_password).save()
        messages.info(request, "注册成功，请登录！")
        # return reverse("youpu:users_login", kwargs={"request": request})
        return render(request, "youpu/users/login.html")
    if request.method == 'GET':
        # return reverse("youpu:users_register", kwargs={"request": request})
        return render(request, "youpu/users/register.html")


# 定义登录逻辑，主要功能：向cookie中加一些数据，方便之后进行校验
@login_exempt
def login(request):
    if request.method == 'POST':
        username = request.POST["username"]
        password = request.POST["password"]
        enc_password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
        # 1、检查是否有对应用户
        try:
            user = User.objects.filter(username=username, password=enc_password)[:1].get()
            if (user is None):
                raise Exception
        except Exception:
            messages.info(request, "信息有误，请重新登录！")
            # return reverse("youpu:users_login", kwargs={"request": request})
            return render(request, "youpu/users/login.html")
        # 2、向session中写入数据,标识用户已登录
        request.session['IS_LOGIN'] = True
        request.session['uname'] = user.username

        request.user = user
        t = loader.get_template("youpu/users/user_detail.html")
        html = t.render({"object": user, "request": request})
        http_response = HttpResponse(html)
        # 3、返回页面
        return http_response

    if request.method == 'GET':
        # 测试文件是否上传到了目录里
        # from static import test
        # test.log_dir()

        return render(request, "youpu/users/login.html")


# 异步发送验证码到指定邮箱
@login_exempt
@csrf_exempt
def get_verify_code(request):
    if request.method == 'POST':
        # 1、检查邮箱是否已注册
        email_dist = "".join(request.POST["email"])
        if (User.objects.filter(email=email_dist).count() != 0):
            # 邮箱已经注册，返回一个code非0的json数据，让前端感知到
            return JsonResponse({"code": 1})
        # 2、生成code，存到redis，调用celery发送邮箱
        random_code = "".join(random.sample('zyxwvutsrqponmlkjihgfedcba', 5))
        # preffix = "users:"
        # cache.set((preffix + email_dist), random_code, timeout=5 * 60)  # 将验证码放到redis中，保持5分钟
        try:
            verifyCode = VerifyCode.objects.get(email=email_dist)
            verifyCode.code = random_code
            verifyCode.save()  # 将新验证码放到数据库中保持
        except VerifyCode.DoesNotExist:
            VerifyCode(email=email_dist, code=random_code).save()  # 新建一个验证码，放到数据库中保持
        # client = ComponentClient(conf.APP_CODE,conf.SECRET_KEY,common_args={'bk_username':"3190932014X"})
        # client.cmsi.send_mail(
        #     {
        #         "receiver":"1007585293@qq.com",
        #         "title":"一次测试",
        #         "content":"这是一次测试",
        #     }
        # )
        send_mail(subject="注册验证码", message="验证码为" + random_code + "，您正在进行【有谱吗】的身份验证，打死也不要告诉别人哦！",
                  from_email="1007585293@qq.com",
                  recipient_list=[email_dist])  # 此处本来是要写为celery任务的，但是仔细想想，好像完全没必要啊，这是ajax请求
        # 4、成功发送，告知前端
        return JsonResponse({"code": 0})


# 注销登录
def logout(request):
    del request.session['IS_LOGIN']
    return redirect("/users/login")


# @login_exempt
# @youpu_login_required
# def user_detail(request):
#     return render(request, "youpu/users/user_detail.html")

@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class UserDetailView(DetailView):
    model = User
    template_name = 'youpu/users/user_detail.html'
    slug_field = "username"
    slug_url_kwarg = "username"

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)
        user = User.objects.get(username=self.request.user.username)
        # 计算用户的各项信息，准备发送给前端进行展示
        context['moments_num'] = user.publisher.filter(reply=False).count()  # 'publisher'为News表中的related_name
        context['article_num'] = user.author.filter(status='P').count()  # 只算已发表的文章
        context['comment_num'] = user.publisher.filter(reply=True).count()  # 动态的评论数
        context['question_num'] = user.q_author.all().count()
        context['answer_num'] = user.a_author.all().count()
        # 互动数 = 动态点赞数+问答点赞数+评论数+私信用户数(双方都有发送和接收私信)
        tmp = set()
        # 我发送私信给了多少不同的用户
        sent_num = user.sent_messages.all()
        for s in sent_num:
            tmp.add(s.recipient.username)
        # 我接收的所有私信来自多少不同的用户
        received_num = user.received_messages.all()
        for r in received_num:
            tmp.add(r.sender.username)
        context['interaction_num'] = user.liked_news.all().count() + user.qa_vote.all().count() + \
                                     context['comment_num'] + len(tmp)

        # 返回一周油力值的列表，供前端展示
        context['oneweek_energy'] = ",".join([str(i) for i in user.get_oneweek_energy()])  # 将数字列表转为“,”间隔的字符串，方便前端解析
        return context


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class UserUpdateView(UpdateView):
    """用户只能更新自己的信息"""

    model = User
    fields = ['username', 'email', 'picture', 'introduction', 'job_title', 'location',
              'personal_url', 'weibo', 'zhihu', 'github']

    template_name = 'youpu/users/user_form.html'

    def get_success_url(self):
        """更新成功后跳转到用户自己的页面"""
        return reverse_lazy("youpu:users_detail", kwargs={"username": self.request.user.username})

    def get_object(self, queryset=None):
        return self.request.user


@method_decorator(login_exempt, name='dispatch')
class NewsListView(ListView):
    """首页动态"""
    model = News
    paginate_by = 20
    template_name = 'youpu/news/news_list.html'

    def get_context_data(self, **kwargs):  # 重写get_context_data方法
        context = super().get_context_data(**kwargs)  # 很关键，必须把原方法的结果拿到并进行返回
        # 由于此处不需要用户的登录，所以我们自定义的youpu_login_required装饰器就无法使用
        # 此处为了修复bug：用户登录了，去到首页【消息列表页】时却没有request.user对象获得
        username = self.request.session.get('uname', "")
        if (User.objects.filter(username=username).count() != 0):
            self.request.user = User.objects.filter(username=username)[:1].get()
        return context

    def get_queryset(self, **kwargs):
        """get_queryset方法是GenericAPIView提供的一个方法，旨在返回queryset数据集，
        而过滤就是要在这个方法返回数据集之前对数据进行筛选，然后返回筛选后的数据
        即可，也就是在需要时可以根据具体要求需要重写这个方法"""
        return News.objects.filter(reply=False).select_related('user', 'parent').prefetch_related('liked')


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class NewsDeleteView(AuthorRequiredMixin, DeleteView):
    """继承DeleteView重写delete方法，使用AJAX响应请求"""
    model = News
    template_name = 'youpu/news/news_confirm_delete.html'
    success_url = reverse_lazy("youpu:news_list")  # 在项目的URLConf未加载前使用


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def post_news(request):
    """发送动态，AJAX POST请求"""
    post = request.POST['post'].strip()
    if post:
        posted = News.objects.create(user=request.user, content=post)
        html = render_to_string('youpu/news/news_single.html', {'news': posted, 'request': request})
        # 发一条动态，增加2点油力值
        add_today_energy(request.user, 2)
        return HttpResponse(html)
    else:
        return HttpResponseBadRequest("内容不能为空！")


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def like_news(request):
    """点赞，AJAX POST请求"""
    news_id = request.POST['news']
    news = News.objects.get(pk=news_id)
    # 取消或者添加赞
    news.switch_like(request.user)
    # 返回赞的数量
    return JsonResponse({"likes": news.count_likers()})


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["GET"])
def get_thread(request):
    """返回动态的评论，AJAX GET请求"""
    news_id = request.GET['news']
    news = News.objects.select_related('user').get(pk=news_id)  # 不是.get(pk=news_id).select_related('user')
    # render_to_string()表示加载模板，填充数据，返回字符串
    news_html = render_to_string("youpu/news/news_single.html", {"news": news})  # 没有评论的时候
    thread_html = render_to_string("youpu/news/news_thread.html", {"thread": news.get_thread()})  # 有评论的时候
    return JsonResponse({
        "uuid": news_id,
        "news": news_html,
        "thread": thread_html,
    })


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def post_comment(request):
    """评论，AJAX POST请求"""
    post = request.POST['reply'].strip()
    parent_id = request.POST['parent']
    parent = News.objects.get(pk=parent_id)
    if post:
        parent.reply_this(request.user, post)
        add_today_energy(request.user, 1)  # 油力值修改
        return JsonResponse({'comments': parent.comment_count()})
    else:  # 评论为空返回400.html
        return HttpResponseBadRequest("内容不能为空！")


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def update_interactions(request):
    """更新互动信息"""
    data_point = request.POST['id_value']
    news = News.objects.get(pk=data_point)
    return JsonResponse({'likes': news.count_likers(), 'comments': news.comment_count()})


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class ArticlesListView(ListView):
    """已发布的文章列表"""
    model = Article
    paginate_by = 5
    context_object_name = "articles"
    template_name = "youpu/articles/article_list.html"  # 可省略

    def get_context_data(self, *args, **kwargs):
        context = super(ArticlesListView, self).get_context_data(*args, **kwargs)
        context['popular_tags'] = Article.objects.get_counted_tags()
        return context

    def get_queryset(self, **kwargs):
        return Article.objects.get_published()


@method_decorator(youpu_login_required, name='dispatch')
class DraftsListView(ArticlesListView):
    """草稿箱文章列表"""

    def get_queryset(self, **kwargs):
        # 当前用户的草稿
        return Article.objects.filter(user=self.request.user).get_drafts()


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
@method_decorator(cache_page(60 * 60), name='get')
class CreateArticleView(CreateView):
    """创建文章"""
    model = Article
    message = "您的文章已创建成功！"  # Django框架中的消息机制
    form_class = ArticleForm
    template_name = 'youpu/articles/article_create.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(CreateArticleView, self).form_valid(form)

    def get_success_url(self):
        """创建成功后跳转"""
        add_today_energy(self.request.user, 3)  # 油力值修改
        messages.success(self.request, self.message)  # 消息传递给下一次请求
        return reverse('youpu:articles_list')


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class DetailArticleView(DetailView):
    """文章详情"""
    model = Article
    template_name = 'youpu/articles/article_detail.html'

    def get_queryset(self):
        return Article.objects.select_related('user').filter(slug=self.kwargs['slug'])


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def like_articles(request):
    """点赞，AJAX POST请求"""
    articles_id = request.POST['articles']
    articles = Article.objects.get(pk=articles_id)
    # 取消或者添加赞
    articles.switch_like(request.user)
    # 返回赞的数量
    return JsonResponse({"likes": articles.count_likers()})


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class EditArticleView(AuthorRequiredMixin, UpdateView):  # 注意类的继承顺序
    """编辑文章"""
    model = Article
    message = "您的文章编辑成功！"
    form_class = ArticleForm
    template_name = 'youpu/articles/article_update.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(EditArticleView, self).form_valid(form)

    def get_success_url(self):
        messages.success(self.request, self.message)
        return reverse('youpu:articles_list')


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class QuestionListView(ListView):
    """所有问题页"""

    queryset = Question.objects.exclude(title='暂无数据，等待占位').select_related('user')
    paginate_by = 10
    context_object_name = "questions"
    template_name = "youpu/qa/question_list.html"

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(QuestionListView, self).get_context_data()
        context["popular_tags"] = Question.objects.get_counted_tags()  # 页面的标签功能
        context["active"] = "all"
        return context


@method_decorator(login_exempt, name='dispatch')
class AnsweredQuestionListView(QuestionListView):
    """已有采纳答案的问题"""

    def get_queryset(self):
        return Question.objects.get_answered()

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(AnsweredQuestionListView, self).get_context_data()
        context["active"] = "answered"
        return context


@method_decorator(login_exempt, name='dispatch')
class UnansweredQuestionListView(QuestionListView):
    """已有采纳答案的问题"""

    def get_queryset(self):
        return Question.objects.get_unanswered()

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(UnansweredQuestionListView, self).get_context_data()
        context["active"] = "unanswered"
        from youpu.tasks import update_wordcloud_data
        return context


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
@method_decorator(cache_page(60 * 60), name='get')
class CreateQuestionView(CreateView):
    """用户提问"""

    form_class = QuestionForm
    template_name = 'youpu/qa/question_form.html'
    message = "问题已提交！"

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(CreateQuestionView, self).form_valid(form)

    def get_success_url(self):
        add_today_energy(self.request.user, 2)  # 油力值修改
        messages.success(self.request, self.message)
        return reverse_lazy("youpu:qa_unanswered_q")


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class QuestionDetailView(DetailView):
    """问题详情页"""

    model = Question
    context_object_name = 'question'
    template_name = 'youpu/qa/question_detail.html'

    def get_queryset(self):
        return Question.objects.select_related('user').filter(pk=self.kwargs['pk'])


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
@method_decorator(cache_page(60 * 60), name='get')
class CreateAnswerView(CreateView):
    """回答问题"""
    model = Answer
    fields = ['content', ]
    message = '您的问题已提交'
    template_name = 'youpu/qa/answer_form.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.question_id = self.kwargs['question_id']
        return super(CreateAnswerView, self).form_valid(form)

    def get_success_url(self):
        add_today_energy(self.request.user, 2)  # 油力值修改
        messages.success(self.request, self.message)
        return reverse_lazy('youpu:qa_question_detail', kwargs={"pk": self.kwargs['question_id']})


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def question_vote(request):
    """给问题投票，AJAX POST请求"""
    question_id = request.POST["question"]
    value = True if request.POST["value"] == 'U' else False  # 'U'表示赞，'D'表示踩
    question = Question.objects.get(pk=question_id)
    users = question.votes.values_list('user', flat=True)  # 当前问题的所有投票用户
    if request.user.pk in users and (question.votes.get(user=request.user).value == value):
        add_today_energy(request.user, -1)  # 取消点赞或点踩，都给点赞（踩）者减少油力值
        question.votes.get(user=request.user).delete()
    else:
        add_today_energy(request.user, 1)  # 点赞或点踩都给点赞（踩）者增加油力值
        question.votes.update_or_create(user=request.user, defaults={"value": value})

    """
    分析逻辑：【详细情况伪码罗列如下】
        # 1.用户首次操作，点赞/踩
        if request.user.pk not in users:
            question.votes.update_or_create(user=request.user, defaults={"value": value})
    
        # 2.用户已经赞过，要取消赞/踩一下
        elif question.votes.get(user=request.user).value:
            if value:
                question.votes.get(user=request.user).delete()
            else:
                question.votes.update_or_create(user=request.user, defaults={"value": value})
    
        # 3.用户已踩过，取消踩/赞一下
        else:
            if not value:
                question.votes.get(user=request.user).delete()
            else:
                question.votes.update_or_create(user=request.user, defaults={"value": value})
    """

    return JsonResponse({"votes": question.total_votes()})


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def answer_vote(request):
    """给回答投票，AJAX POST请求"""
    answer_id = request.POST["answer"]
    value = True if request.POST["value"] == 'U' else False  # 'U'表示赞，'D'表示踩
    answer = Answer.objects.get(uuid_id=answer_id)
    users = answer.votes.values_list('user', flat=True)  # 当前回答的所有投票用户

    if request.user.pk in users and (answer.votes.get(user=request.user).value == value):
        add_today_energy(request.user, -1)  # 减少油力值
        answer.votes.get(user=request.user).delete()
    else:
        add_today_energy(request.user, 1)  # 增加油力值
        answer.votes.update_or_create(user=request.user, defaults={"value": value})

    return JsonResponse({"votes": answer.total_votes()})


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def accept_answer(request):
    """
    接受回答，AJAX POST请求
    已经被接受的回答用户不能取消
    """
    answer_id = request.POST["answer"]
    answer = Answer.objects.get(pk=answer_id)
    # 如果当前登录用户不是提问者，抛出权限拒绝错误
    if answer.question.user.username != request.user.username:
        raise PermissionDenied
    answer.accept_answer()
    # 生成一条通知，通知回答者
    add_one_notification(request.user, answer.user, 'W', answer)
    add_today_energy(answer.user, 3)  # 回答被采纳者增加油力值
    return JsonResponse({'status': 'true'}, status=200)


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class MessagesListView(ListView):
    model = Message
    template_name = "youpu/messager/message_list.html"

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(MessagesListView, self).get_context_data()
        # 获取除当前登录用户外的所有用户，按个人信息修改的时间降序排列，每次显示10个人
        # context['users_list'] = User.objects.filter(is_active=True).exclude(
        context['users_list'] = User.objects.all().exclude(
            username=self.request.user
        ).order_by('-updated_at')[:10]
        # 最近一次私信互动的用户
        last_conversation = Message.objects.get_most_recent_conversation(self.request.user)
        context['active'] = last_conversation
        return context

    def get_queryset(self):
        """最近私信互动的内容"""
        active_user = Message.objects.get_most_recent_conversation(self.request.user)
        return Message.objects.get_conversation(self.request.user, active_user)


@method_decorator(login_exempt, name='dispatch')
class ConversationListView(MessagesListView):
    """与指定用户的私信内容"""

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(ConversationListView, self).get_context_data()
        activeUser = User.objects.get(username=self.kwargs["username"])
        context['active'] = activeUser
        return context

    def get_queryset(self):
        active_user = get_object_or_404(User,
                                        username=self.kwargs["username"])
        return Message.objects.get_conversation(self.request.user, active_user)


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["POST"])
def send_message(request):
    """发送消息，AJAX POST请求"""
    sender = request.user
    recipient_username = request.POST['to']
    recipient = User.objects.get(username=recipient_username)
    message = request.POST['message']
    if len(message.strip()) != 0 and sender != recipient:
        # 1.将新增的message写到数据库
        msg = Message.objects.create(
            sender=sender,
            recipient=recipient,
            message=message
        )

        # 2.【已弃用】调用consumer向前端推送新消息
        # channel_layer = get_channel_layer()
        # payload = {
        #     'type': 'receive',
        #     'message': render_to_string('youpu/messager/single_message.html', {"message": msg}),
        #     'sender': sender.username
        # }
        # # group_send(group: 所在组-接收者的username, message: 消息内容)
        # async_to_sync(channel_layer.group_send)(recipient.username, payload)

        add_today_energy(sender, 1)  # 增加油力值
        return render(request, 'youpu/messager/single_message.html', {'message': msg})

    return HttpResponse()


@login_exempt
@youpu_login_required
@ajax_required
@require_http_methods(["GET"])
def receive_message(request):
    """接收消息,处理AJAX发出的GET请求"""
    msg_recipient_id = request.GET['me']
    msg_sender_id = request.GET['you']
    try:
        # 1.获取最新未读消息
        msg = Message.objects.get(recipient=msg_recipient_id, sender=msg_sender_id, unread=1)
        # 2.将消息置为已读,并收集所有消息
        msg.mark_as_read()
        # 3.返回全部消息
        return render(request, 'youpu/messager/single_message.html', {'message': msg})
    except Message.DoesNotExist:
        # 未有新消息，则不进行处理
        return HttpResponse("good")
    except Message.MultipleObjectsReturned:
        # 如果有多条消息被发送，就先全部标记为已读，并告知前端跳转至私信列表页
        messages = Message.objects.filter(recipient=msg_recipient_id, sender=msg_sender_id, unread=1)
        for message in messages:
            message.mark_as_read()
        return HttpResponse("error")


@method_decorator(login_exempt, name='dispatch')
@method_decorator(youpu_login_required, name='dispatch')
class NotificationUnreadListView(ListView):
    """未读通知列表"""
    model = Notification
    context_object_name = 'notification_list'
    template_name = 'youpu/notifications/notification_list.html'

    def get_queryset(self, **kwargs):
        return self.request.user.notifications.unread()


@login_exempt
@youpu_login_required
def mark_all_as_read(request):
    """将所有通知标为已读"""
    request.user.notifications.mark_all_as_read()
    redirect_url = request.GET.get('next')

    messages.add_message(request, messages.SUCCESS, f'用户{request.user.username}的所有通知标为已读')

    if redirect_url:
        return redirect(redirect_url)

    return redirect('youpu:notifications_unread')


@login_exempt
@youpu_login_required
def mark_as_read(request, slug):
    """根据slug标为已读"""
    notification = get_object_or_404(Notification, slug=slug)
    notification.mark_as_read()

    redirect_url = request.GET.get('next')

    messages.add_message(request, messages.SUCCESS, f'通知{notification}标为已读')

    if redirect_url:
        return redirect(redirect_url)

    return redirect('youpu:notifications_unread')


@login_exempt
@youpu_login_required
def get_latest_notifications(request):
    """最近的未读通知"""
    notifications = request.user.notifications.get_most_recent()
    return render(request, 'youpu/notifications/most_recent.html',
                  {'notifications': notifications})


@login_exempt
@csrf_exempt
@youpu_login_required
def get_hotlist_index(request):
    """跳转到热榜界面"""
    hotlist_article = HotList.objects.filter(type="A")
    hotlist_question = HotList.objects.filter(type="Q")
    wordcloud_object = Wordcloud.objects.all()[0]
    return render(request, 'youpu/hotlist/hotlist_index.html',
                  {'hotlist_article': hotlist_article, 'hotlist_question': hotlist_question,
                   'wordcloud_object': wordcloud_object})


# @login_exempt
# @csrf_exempt
# @youpu_login_required
# def get_hotlist_questions(request):
#     pass
#
#
# @login_exempt
# @csrf_exempt
# @youpu_login_required
# def get_hotlist_articles(request):
#     pass


@login_exempt
@youpu_login_required
def get_search_reuslt_list(requset):
    return render(requset, 'youpu/search_result_list.html')
